package com.study.easyexcel.fill;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.study.easyexcel.entity.TemplateData;
import com.study.easyexcel.util.FileUtil;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class FillUtil {
    public static final String TEMPLATE_FILE_NAME="A-template.xlsx";
    public static void main(String[] args) {
        fillExcel(data(),"A-template.xlsx",null);
    }
    /**
     * @param data  要填充的数据
     * @param templatePath 模版文件
     * @param outputPath   输出文件流
     */
    public static void fillExcel(List<TemplateData> data, String templatePath, String outputPath){
        if(StringUtils.isBlank(templatePath)){
            templatePath = TEMPLATE_FILE_NAME;
        }
        if(StringUtils.isBlank(outputPath)){
            outputPath = getAbsoluteFileName();
        }
        InputStream templateStream =  FileUtil.getFileInputStream(templatePath);
        OutputStream fileOutputStream = FileUtil.getFileOutPutStream(outputPath);
        fillExcel(data,templateStream,fileOutputStream);
    }



    /**
     * @param data  要填充的数据
     * @param templateStream 模版文件
     * @param outputStream   输出文件流
     */
    public static void fillExcel(List<TemplateData> data, InputStream templateStream, OutputStream outputStream){
        if(data==null){
            throw new RuntimeException("要填充的数据不能为空");
        }
        if(templateStream==null){
            throw new RuntimeException("模版文件流不能为空");
        }
        if(outputStream==null){
            throw new RuntimeException("输出文件流不能为空");
        }
        try(ExcelWriter writer = EasyExcel.write(outputStream).withTemplate(templateStream).build()){
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            writer.fill(data,writeSheet);
            writer.finish();
        }
    }

    private static List<TemplateData> data() {
        List<TemplateData> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            TemplateData td =new TemplateData( "dxtm"+i, 1,  "mode"+i, 3d, 1d, 2d, 3d, 1d, 2d, 3d, 1d, 2d, 3d, 1d, 2d,
                   2,  "模式222"+i, 3d, 1d, 2d, 3d, 1d, 2d, 3d, 1d, 2d, 3d, 1d, 2d);
            list.add(td);


        }
        return list;
    }

    public static String getAbsoluteFileName(){
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String fileName = FileUtil.getUserDir() + File.separator+"输出目录" +File.separator+
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"))+File.separator
                +"A自动处理系统-循环温升模板_"+ date + ".xlsx";
        return fileName;
    }
}
